import React, {PureComponent} from "react";
import {hideExport, updateExportModel, updateRateDataSource} from "./actions";
import {connect} from "react-redux";
import {Form, InputNumber, Modal, notification, Select, Table} from "antd";
import {getPrincipal} from "../../lib/identity";
import {tableProps} from "../../lib/ui";
import {exportByType3} from "../zadOrderPayable/actions";
import {formatDate} from "../../lib/func";

const {Option} = Select;

class ExportModal extends PureComponent {
    state = {'currency': "", 'selectId': "", bankInfoId: undefined};
    handleExport = () => {
        const bankInfoId = this.state.bankInfoId;
        if (bankInfoId === null || bankInfoId === undefined || bankInfoId.length === 0) {
            notification.error({
                message: '请选择银行账号信息'
            });
            return;
        }
        const currency = this.state.currency;
        const {form: {validateFields}, dispatch, rateData, filter} = this.props;
        // 格式化日期 formatDate
        for (const filterKey in filter) {
            if (filterKey.indexOf("Date") >= 0 || filterKey.indexOf("Time") >= 0) {
                filter[filterKey] = formatDate(filter[filterKey]);
            }
        }
        if ("无需转换" !== currency) {
            // 如果选了币种，需要判断币种列表是否大于0
            if (rateData === undefined || rateData === null || rateData.length === 0) {
                notification.error({
                    message: '请先维护一条符合日期有效期范围的汇率再进行操作'
                });
                return;
            }
        }
        validateFields((err, values) => {
            if (!err) {
                const exportData = {
                    ...filter,
                    bankInfoId: bankInfoId,
                    tableName: "zadOrderReceivable",
                    rateList: rateData,
                    type: "IN",
                    currency: currency,
                    userId: getPrincipal().id
                };
                dispatch(exportByType3(exportData)).then(action => {
                    if (action.error !== true) {
                        const fileName = action.payload;
                        dispatch(hideExport());
                        window.location.href = "/file/" + fileName;
                    }
                });
            }
        });
    };

    handleCancel = () => {
        const {dispatch} = this.props;
        dispatch(hideExport());
    };

    onChange = value => {
        const {rateData} = this.props;
        const found = rateData.find(fee => fee.id === this.state.selectId);
        if (found) {
            found.rate = value;
        }
    };

    changeBank = value => {
        this.setState({bankInfoId: value});
    };

    onChangeInvoiceDate = (value, dateString) => {
        document.getElementById("invoiceDate").value = dateString;
    };

    onChangeSettlementDate = (value, dateString) => {
        document.getElementById("settlementDate").value = dateString;
    };

    changeRemark = value => {
        document.getElementById("remark").value = value;
    };

    handleSelectChange = value => {
        this.setState({'currency': value});
        const {dispatch, rateList, model, form: {getFieldsValue}} = this.props;
        model.currency = value;
        dispatch(updateExportModel({...getFieldsValue(), ...model}));
        if ("无需转换" !== value) {
            const rateData = [];
            rateList.forEach(item => {
                if (item.fromRate === value || item.toRate === value) {
                    delete item.createTime;
                    delete item.startDate;
                    delete item.endDate;
                    rateData.push(item);
                }
            });
            dispatch(updateRateDataSource(rateData));
        } else {
            dispatch(updateRateDataSource([]));
        }
    };

    render() {
        const {
            model, currencyList, visible, loading, rateData, form: {getFieldDecorator}, filter, bankList
        } = this.props;
        const data = [];
        delete filter.userId;
        for (let key of Object.keys(filter)) {
            const value = filter[key];
            data.push({"key": key, "value": value});
        }
        const rateColumns = [
            {
                title: '转换前币种',
                dataIndex: 'fromRate',
                width: 100
            },
            {
                title: '转换后币种',
                dataIndex: 'toRate',
                width: 100
            },
            {
                title: '汇率',
                dataIndex: 'rate',
                width: 100,
                render: (text) => <InputNumber defaultValue={text} onChange={this.onChange}/>
            }
        ];
        return (
            <Modal
                title="导出设置"
                visible={visible}
                onOk={this.handleExport}
                onCancel={this.handleCancel}
                confirmLoading={loading}
                okText="导出"
                cancelText="取消"
                width="40%"
            >
                <div style={{margin: 10}}>
                    选择币种：<Select
                    placeholder="请选择一种转换方式"
                    onChange={this.handleSelectChange}
                    style={{width: 180}}
                    value={this.state.currency}
                >
                    <Option value="无需转换">无需转换</Option>
                    {currencyList.map(item => (
                        <Option value={item.name} key={item.name}>
                            {item.name}
                        </Option>
                    ))}
                </Select>
                </div>
                {model.currency !== "无需转换" && rateData.length > 0 ?
                    <Table
                        {...tableProps}
                        components={this.components}
                        onRow={record => {
                            return {
                                onClick: event => {
                                    this.rowOnClick(record)
                                }, // 点击行
                            };
                        }}
                        rowClassName={() => 'editable-row'}
                        bordered
                        dataSource={rateData}
                        columns={rateColumns}
                    /> : null}
                <div style={{margin: 10}}>
                    银行账号信息：<Select style={{width: 300}}
                                   placeholder="请选择银行账号信息"
                                   onChange={this.changeBank}
                >
                    {bankList.map(bank => (
                        <Option value={bank.id} key={bank.mark}>
                            {bank.mark + " 人民币账户" + bank.rmbAccount + " 美元账户" + bank.usdAccount}
                        </Option>
                    ))}
                </Select>
                </div>
                <form
                    id="exportReceivable"
                    method="post"
                    target="_blank"
                    action="/api/zadOrder/exportByType3"
                >
                    <input
                        name="currency"
                        type="hidden"
                        value={model.currency}
                    />
                    <input
                        name="userId"
                        type="hidden"
                        value={getPrincipal().id}
                    />
                    <input
                        name="type"
                        type="hidden"
                        value="IN"
                    />
                    <input
                        name="rateListStr"
                        type="hidden"
                        value={JSON.stringify(rateData)}
                    />
                    <input
                        name="tableName"
                        type="hidden"
                        value="zadOrderReceivable"
                    />
                    <input
                        id="invoiceDate"
                        name="invoiceDate"
                        type="hidden"
                    />
                    <input
                        id="settlementDate"
                        name="settlementDate"
                        type="hidden"
                    />
                    <input
                        id="remark"
                        name="remark"
                        type="hidden"
                    />
                    <input
                        id="bankInfoId"
                        name="bankInfoId"
                        type="hidden"
                    />
                    {/*{getPrincipal().admin ? <input
                        name="orgId"
                        type="hidden"
                        value={filter.organizationId}
                    /> : <input
                        name="orgId"
                        type="hidden"
                        value={getCurrentOrganization()}
                    />}*/}
                    {data.map(item => (
                        <input
                            id={item.key}
                            name={item.key}
                            type="hidden"
                            value={item.value}
                        />
                    ))}
                </form>
            </Modal>
        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.zadOrderReceivable.exportReceivable,
        clientList: state.zadOrderReceivable.list.clientList,
        currencyList: state.zadOrderReceivable.list.currencyList,
        rateList: state.zadOrderReceivable.list.rateList,
        feeList: state.zadOrderReceivable.list.feeList,
        filter: state.zadOrderReceivable.list.filter,
        bankList: state.bankInfo.list.dataSource
    };
};

const mapPropsToFields = ({model}) => {
    const fields = {};
    Object.keys(model).forEach(field => {
        fields[field] = Form.createFormField({value: model[field]});
    });
    return fields;
};

export default connect(mapStateToProps)(Form.create({mapPropsToFields})(ExportModal));
